<?php
/**
 * Created by muniao.
 * User: muniao
 * Date: 2018/7/25
 * Time: 9:48
 */

namespace app\api\controller\android\v12;


use app\api\model\Authority;
use app\api\model\Capital;
use think\Controller;
use think\Request;
use think\Db;


class SiteInspection extends Controller
{
    protected $model;
    protected $us;
    
    
    public function _initialize()
    {
        $this->model = new Authority();
        $this->us    = Authority::check(1);
        
    }
    
    public function getList()
    {
        $data                        = Authority::param(['orderId', 'type']);
        $auxiliary_delivery_node     = \db('auxiliary_delivery_node')
            ->field('count(auxiliary_delivery_schedul_id) as nodeId,sum(DISTINCT if(auxiliary_delivery_node.state=1,1,0)) as nodeIds,auxiliary_delivery_schedul_id')
            ->group('auxiliary_delivery_schedul_id')
            ->buildSql();
      
        $auxiliary_delivery_schedule = \db('auxiliary_delivery_schedule')
            ->field('count(auxiliary_delivery_schedule.id) as scheduleId,node.nodeId,sum(nodeIds) as nodeIds,node.auxiliary_delivery_schedul_id,auxiliary_delivery_schedule.auxiliary_project_list_id')
            ->join([$auxiliary_delivery_node => 'node'], 'node.auxiliary_delivery_schedul_id=auxiliary_delivery_schedule.id', 'left')
            ->whereNull('auxiliary_delivery_schedule.delete_time')
            ->group('auxiliary_project_list_id')
            ->buildSql();
        
        
        $capital = db('auxiliary_project_list')
            ->join([$auxiliary_delivery_schedule => 'schedule'], 'auxiliary_project_list.id=schedule.auxiliary_project_list_id', 'left')
            ->join('capital', 'capital.capital_id=auxiliary_project_list.capital_id', 'left')
            ->field('auxiliary_project_list.capital_id,schedule.scheduleId,ifnull(schedule.nodeId,0) as nodeId,ifnull(schedule.nodeIds,0) as nodeIds,schedule.auxiliary_delivery_schedul_id,concat(capital.class_b,"(",square,"/",company,")") as class_b,capital.cooperation,auxiliary_project_list.auxiliary_id,auxiliary_project_list.id')
            ->where('order_id', $data['orderId'])
            ->where('capital.types', 1)
            ->whereNull('auxiliary_project_list.delete_time');
        if ($data['type'] == 1) {
            $capital->where(
                function ($quer) {
                    $quer->whereNull('nodeId')->whereOr('scheduleId !=nodeIds');;
                });
        } else {
            $capital->where('scheduleId = nodeIds');
        }
        $capital = $capital->group('auxiliary_project_list.capital_id')
            ->select();
    
        foreach ($capital as $k => $item) {
            $username                      = Db::connect(config('database.db2'))->table('app_user_order_capital_relation')->where('capital_id', $item['capital_id'])->join('app_user', 'app_user.id=app_user_order_capital_relation.user_id', 'left')->where('order_id', $data['orderId'])->column('app_user.username');
            $capital[$k]['class_b']        .= "         " . implode($username, '/');
            $capital[$k]['Specifications'] = implode(db('capital_value')->where('capital_id', $item['capital_id'])->column('title'), '/');
            $auxiliary_delivery_schedule   = db('auxiliary_delivery_schedule')->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_delivery_schedule.auxiliary_interactive_id', 'left')->field('auxiliary_interactive.title,auxiliary_interactive.main_node,auxiliary_delivery_schedule.id')->where('auxiliary_project_list_id', $item['id'])->select();
            foreach ($auxiliary_delivery_schedule as $p => $value) {
                $app_user_order_nodes = db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', $value['id'])->select();
                if (!empty($app_user_order_nodes)) {
                    $paths = [];
                    foreach ($app_user_order_nodes as $l) {
                        $app_user_order_nodes_list = Db::connect(config('database.db2'))->table('app_user_order_node')
                            ->join('app_user', 'app_user.id=app_user_order_node.user_id', 'left')
                            ->join(config('database')['database'] . '.user', 'user.user_id=app_user_order_node.user_id', 'left')
                            ->field('app_user_order_node.id,app_user_order_node.resource_ids,app_user_order_node.created_at,if(app_user_order_node.distinguish=1,user.username,app_user.username) as username,app_user_order_node.distinguish')
                            ->whereIn('app_user_order_node.id', $l['node_id'])->select();
                        $pathId                    = implode(array_column($app_user_order_nodes_list, 'resource_ids'), ',');
                        $path                      = Db::connect(config('database.db2'))->table('common_resource')->where('status', 1)->whereIn('id', $pathId)->field('mime_type,path,id')->select();
//                        var_dump($path);
                        
                        foreach ($path as $k1 => $o) {
                            
                            $list['path']       = 'https://images.yiniao.co/' . $o['path'];
                            $list['id']         = $o['id'];
                            $list['type']       = $app_user_order_nodes_list[0]['distinguish'];
                            $list['username']   = $app_user_order_nodes_list[0]['username'];
                            $list['created_at'] = date('Y-m-d H:i', $app_user_order_nodes_list[0]['created_at']);
                            $paths[]            = $list;
                        }
                        
                        
                    }
                    $auxiliary_delivery_schedule[$p]['data']   = $paths;
                    $auxiliary_delivery_schedule[$p]['state']  = $app_user_order_nodes[0]['state'];
                    $auxiliary_delivery_schedule[$p]['reason'] = $app_user_order_nodes[0]['reason'];
                    $auxiliary_delivery_schedule[$p]['node_id'] = $app_user_order_nodes[0]['node_id'];
                } else {
                    $auxiliary_delivery_schedule[$p]['state']  = 0;
                    $auxiliary_delivery_schedule[$p]['reason'] = '';
                    $auxiliary_delivery_schedule[$p]['data']   = [];
                    $auxiliary_delivery_schedule[$p]['node_id']   = 0;
                }
                
            }
            
            $capital[$k]['data'] = $auxiliary_delivery_schedule;
        }
        
        
        r_date($capital, 200);
    }
    
    
    public function info()
    {
        $data                = Authority::param(['id']);
        $list                = db('auxiliary_delivery_schedule')
            ->join('auxiliary_interactive', 'auxiliary_interactive.id=auxiliary_delivery_schedule.auxiliary_interactive_id', 'left')
            ->field('auxiliary_interactive.shot,auxiliary_interactive.acceptance_criteria,auxiliary_interactive.picture_url')
            ->where('auxiliary_delivery_schedule.id', $data['id'])
            ->find();
        $list['picture_url'] = empty($list['picture_url']) ? [] : unserialize($list['picture_url']);
        r_date($list, 200);
    }
    
    public function toExamine()
    {
        $data                    = Request::instance()->post();
        $nodeIds                 = json_decode($data['nodeIds'], true);
  
        $nodeIds                 = implode($nodeIds, ',');
     
        $auxiliary_delivery_node = db('auxiliary_delivery_node')->whereIn('auxiliary_delivery_schedul_id', $nodeIds)->update(['state' => $data['state'], 'reason' => $data['reason'], 'audit_time' => time()]);
        if ($auxiliary_delivery_node) {
            r_date(null, 200);
        }
        r_date(null, 300);
    }
    
    public function addNode()
    {
        db()->startTrans();
        Db::connect(config('database.db2'))->startTrans();
        $data = Request::instance()->post();
        try {
            $params   = request()->only(['order_id', 'title', 'describe', 'lng', 'lat', 'address', 'id']);
            $resource = json_decode($data['resource'], true);
            if (!empty($resource)) {
                $params['resource_ids'] = implode(',', $this->addResourceIds($resource));
            }
            $params['describe']    = '';
            $params['user_id']     = $this->us['user_id'];
            $params['type']        = 2;
            $params['status']      = 1;
            $params['distinguish'] = 1;
            $params['created_at']  = time();
            $params['updated_at']  = time();
            $orderNode             = Db::connect(config('database.db2'))->table('app_user_order_node')->insertGetId($params);
            \db('auxiliary_delivery_node')->insert(['auxiliary_delivery_schedul_id' => $data['nodeChildId'], 'state' => 0, 'node_id' => $orderNode, 'mast_id' => $this->us['user_id'], 'type' => 2]);
            db()->commit();
            Db::connect(config('database.db2'))->commit();
            r_date(null, 200);
            
        } catch (\Exception $e) {
            Db::connect(config('database.db2'))->rollBack();
            db()->rollBack();
            r_date(null, 300, $e->getMessage());
        }
    }
    
    /**
     * 添加资源返回ID
     * @param $resources
     * @return array
     */
    public function addResourceIds($resources)
    {
        
        $resource_ids = [];
        foreach ($resources as $item) {
            if (!isset($item['mime_type']) || !isset($item['file_path'])) {
                r_date(null, 300, '资源格式错误');
            }
            $info = Db::connect(config('database.db2'))->table('common_resource')->where('path', $item['file_path'])->find();
            
            if ($info !== null) {
                $resource_ids[] = $info['id'];
            } else {
                $resource_ids[] = Db::connect(config('database.db2'))->table('common_resource')->insertGetId(['mime_type' => $item['mime_type'], 'path' => $item['file_path'], 'size' => $item['size'] ?? 0, 'created_at' => time()]);
            }
        }
        return $resource_ids;
    }
    
    public function del()
    {
        $data                    = Request::instance()->post();
        $app_user_order_node= Db::connect(config('database.db2'))->table('app_user_order_node')->where('find_in_set(:id,resource_ids)', ['id' => $data['nodeId']])->find();
        $auxiliary_delivery_node = db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $data['id'])->where('node_id',$app_user_order_node['id'])->find();
       
        $resource_ids            = explode(',',$app_user_order_node['resource_ids']);
        foreach ($resource_ids as $k => $o) {
            if ($o == $data['nodeId']) {
                unset($resource_ids[$k]);
            }
            
        }
        
        if (count($resource_ids) == 0) {
            db('auxiliary_delivery_node')->where('auxiliary_delivery_schedul_id', $data['id'])->where('node_id',$app_user_order_node['id'])->delete();
            Db::connect(config('database.db2'))->table('app_user_order_node')->where('id', $auxiliary_delivery_node['node_id'])->delete();
        }else{
            
            Db::connect(config('database.db2'))->table('app_user_order_node')->where('id', $auxiliary_delivery_node['node_id'])->update(['resource_ids'=>implode($resource_ids,',')]);
        }
        r_date(null, 200);
    }
    
}